<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\model;

use think\Model;
use app\admin\model\Config as ConfigModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Sample as SampleModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Give as GiveModel;
use think\Db;

/**
 * 账单表模型
 */
class Finance extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mill_order_archives_initial_price';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //根据面积表信息获取单价信息
    public static function getPriceInfo($data = []){
        //判断是面积表ID，还是面积表信息
        if(!is_array($data))$data = Db::name('mill_order_archives')->where(['id'=>$data])->find();
        $tgd_where = [
            ['type','=',0],
            ['order_id','=',$data['order_id']],
            ['color','=',$data['color']],
            ['thickness','=',$data['thickness']],
            ['model','=',$data['model']],
        ];

        $archives_price = Db::name('mill_order_archives_initial_price')->where($tgd_where)->find();

        return $archives_price;
    }

    //获取工程计价信息
    public static function getOrderPriceInfo($data = []){
        $tgd_where = [
            ['order_id','in',$data['order_ids']],
        ];

        $archives_price = Db::name('mill_order_archives_initial_price')->where($tgd_where)->column('price',"CONCAT(order_id,color,thickness,model,type)");

        return $archives_price;
    }

    // 表格制作
    //print 0:编辑模式 1:打印模式 2:导出模式
    public static function fromArchivesTabale($data = [],$print = 0){

        //表头
        $table_head = $data['table_head'];

        //------------------------------------面积表明细--------------------------------------
        $table_data[] = ["[14:1]<div class='dch-th'>产品详情列表</div>"];
        foreach ($data['table_archives']['head'] as &$ak){
            $ak = "<div class='dch-th'>{$ak}</div>";
        }

        $table_data[] = $data['table_archives']['head'];
        foreach ($data['table_archives']['data'] as $av){
            $table_data[] = $av;
        }
        $table_data[] = [
            "[2:1]<div class='dch-th'>合计</div>",
            "[1:1]<div class='dch-th'></div>",
            "[1:1]<div class='dch-th allpric'>{$data['number_sum']}</div>",
            "[1:1]<div class='dch-th'></div>",
            "[1:1]<div class='dch-th'></div>",
            "[1:1]<div class='dch-th'></div>",
            "[1:1]<div class='dch-th allpric'>{$data['area_sum']}</div>",
            "[1:1]<div class='dch-th'></div>",
            "[1:1]<div class='dch-th'></div>",
            "[1:1]<div class='dch-th'></div>",
            "[1:1]<div class='dch-th'></div>",
            "[1:1]<div class='dch-th'></div>",
            "[1:1]<div class='dch-th'></div>",
        ];

        //-------------------------------------基本计价---------------------------------------
        $table_data[] = ["[14:1]"];
        $table_data[] = ["[14:1]<div class='dch-th'>基本计价</div>"];
        $data['table_archives_group']['colspan'] = ["[1:1]","[3:1]","[3:1]","[1:1]","[2:1]","[3:1]","[1:1]"];
        foreach ($data['table_archives_group']['head'] as $agk=>$agv){
            $agv = "{$data['table_archives_group']['colspan'][$agk]}<div class='dch-th'>{$agv}</div>";
            $data['table_archives_group']['head'][$agk] = $agv;
        }
        $table_data[] = $data['table_archives_group']['head'];

        $sum_info['address_number'] = 0;
        $sum_info['address_area'] = 0;
        $sum_info['address_price'] = 0;
        $sum_price_1 = 0;
        $i = 1;
        foreach ($data['table_archives_group']['data'] as $tgk=>$tgd){

            //设置唯一标识
            $data_group = 'group_'.md5(
                    $tgd['thickness'].'|||'
                    .$tgd['color'].'|||'
                    .$tgd['model'].'|||'
                );

            //获取面积表计价信息
            $archives_price = self::getPriceInfo($tgd);
            unset($tgd['order_id']);

            $price = 0;
            $price_id = 0;
            $price_time = time();
            if(!empty($archives_price)){
                $price_id = $archives_price['id'];
                $price = $archives_price['price'];
                $price_time = $archives_price['create_time'];
            }

            //----------------------单价-------------------------
            $price_html = '
                    <input type="hidden" name="price_arr['.$i.'][id]" value="'.$price_id.'">
                    <input type="hidden" name="price_arr['.$i.'][order_id]" value="'.$data['id'].'">
                    <input type="hidden" name="price_arr['.$i.'][create_time]" value="'.$price_time.'">
                    <input type="hidden" name="price_arr['.$i.'][color]" value="'.$tgd['color'].'">
                    <input type="hidden" name="price_arr['.$i.'][thickness]" value="'.$tgd['thickness'].'">
                    <input type="hidden" name="price_arr['.$i.'][model]" value="'.$tgd['model'].'">
                    <input id="'.$data_group.'_price" class="form-control group_price" type="number" name="price_arr['.$i.'][price]" value="'.$price.'" data-one_area_sum="'.$tgd['one_area_sum'].'" data-i="'.$i.'" data-sum-price="group_price_1">
                ';
            if($print)$price_html = $price;
            $tgd['price'] = $price_html;
            $tgd['price_sum'] = '<span class="group_price_all group_price_1" id="area_sum_'.$i.'">'.round($price*$tgd['one_area_sum'],2).'</span>';

            unset($tgd['archives_ids']);

            $sum_info['address_number'] += $tgd['number_sum'];
            $sum_info['address_area'] += $tgd['one_area_sum'];
            $sum_price_1 += round($price*$tgd['one_area_sum'],2);

            //板厚统计
            if(!isset($table_group_data_type_sarr[$data['id']]['thickness'][$tgd['thickness']]))$table_group_data_type_sarr[$data['id']]['thickness'][$tgd['thickness']] = 0;
            $table_group_data_type_sarr[$data['id']]['thickness'][$tgd['thickness']] += $tgd['one_area_sum'];

            $data['table_archives_group']['data'][$tgk] = $tgd;

            $i++;
        }
        $data['table_archives_group']['data'][] = [
            "<div class='dch-th'>合计</div>",
            "<div class='dch-th'></div>","<div class='dch-th'></div>",
            "<div class='dch-th allpric'>{$sum_info['address_number']}</div>",
            "<div class='dch-th allpric'>{$sum_info['address_area']}</div>",
            "<div class='dch-th'></div>",
            "<div class='dch-th allpric sum_group_price_1' >".$sum_price_1."</div>"
        ];

        foreach ($data['table_archives_group']['data'] as $tgd){
            $tgd_i = 0;
            $new_ttav = [];
            foreach ($tgd as $tgdk=>$tgdv){
                $new_ttav[] = "{$data['table_archives_group']['colspan'][$tgd_i]}<div class=''>{$tgdv}</div>";
                $tgd_i++;
            }
            $table_data[] = $new_ttav;
        }

        //-------------------------------------加价计价---------------------------------------
        $table_data[] = ["[14:1]"];
        $table_data[] = ["[14:1]<div class='dch-th'>加价计价</div>"];
        $jia_colspan = ["[3:1]","[2:1]","[3:1]","[3:1]","[3:1]"];
        $jia_head = ["加价项目","数量","单价(元)","合计金额(元)","备注"];
        $jia_data = [];
        $sum_price_2 = 0;

        foreach ($jia_head as $agk=>$agv){
            $agv = "{$jia_colspan[$agk]}<div class='dch-th'>{$agv}</div>";
            $jia_head[$agk] = $agv;
        }
        $table_data[] = $jia_head;

        //类型 0:面积价 1:铝锭价 2:焊缝 3: 刨槽 4:开孔
        $tgd_type_arr = [
            //合计开槽
            ['field'=>'slot','title'=>'刨槽长度','type'=>2,'sum_eq'=>1],
            //合计焊缝
            ['field'=>'weld','title'=>'焊缝长度','type'=>3,'sum_eq'=>1],
            //矩管长度
            ['field'=>'torque','title'=>'开孔个数','type'=>4,'sum_eq'=>1],
        ];
        if(count($tgd_type_arr)>0){
            foreach ($tgd_type_arr as $ttav){

                $i++;
                $ld_field = $ttav['field'];
                $ld_title = $ttav['title'];
                $ld_sum_eq = $ttav['sum_eq'];
                $ld_type = $ttav['type'];//类型 0:面积价 1:铝锭价 2:焊缝 3: 刨槽 4:开孔

                $price_arr_where = ['order_id'=>$data['id'],'type'=>$ld_type];
                $tgpv = Db::name('mill_order_archives_initial_price')->where($price_arr_where)->find();

                $ld_id = !empty($tgpv['id'])?$tgpv['id']:'';
                $ld_order_id = !empty($tgpv['order_id'])?$tgpv['order_id']:$data['id'];
                $ld_time = !empty($tgpv['create_time'])?$tgpv['create_time']:time();
                $ld_pirce = !empty($tgpv['price'])?$tgpv['price']:0;
                $ld_note = !empty($tgpv['note'])?$tgpv['note']:'';
                $ld_row_area = $data[$ld_field];

                $ld_price_sum = round($ld_row_area*$ld_pirce,2);//四舍五入，保留2位

                //数量
                $ld_field_html = '<div class="'.$ld_field.'_sum">'.$ld_row_area.'</div>';
                //单价
                $ld_input_html = '
                <input type="hidden" name="price_arr['.$i.'][id]" value="'.$ld_id.'">
                <input type="hidden" name="price_arr['.$i.'][order_id]" value="'.$ld_order_id.'">
                <input type="hidden" name="price_arr['.$i.'][create_time]" value="'.$ld_time.'">
                <input type="hidden" name="price_arr['.$i.'][type]" value="'.$ld_type.'">
                <input type="hidden" name="price_arr['.$i.'][row_area]" value="'.$ld_row_area.'" class="'.$ld_field.'_row_area">

                <input class="form-control '.$ld_field.'_val group_price" type="number" name="price_arr['.$i.'][price]" value="'.$ld_pirce.'" data-one_area_sum="'.$ld_row_area.'"  data-i="'.$i.'" data-sum-price="group_price_2">
                ';
                //备注
                $ld_note_html = '
                <input class="form-control" type="text" name="price_arr['.$i.'][note]" value="'.$ld_note.'">
                ';
                if($print){
                    $ld_input_html = $ld_pirce;
                    $ld_note_html = $ld_note;
                }
                $ld_price_html = '<span class="group_price_all group_price_2" id="area_sum_'.$i.'">'.$ld_price_sum.'</span>';

                $new_ttav = [$ld_title,'',$ld_input_html,$ld_price_html,$ld_note_html];
                $new_ttav[$ld_sum_eq] = $ld_field_html;

                $jia_data[] = $new_ttav;

                $sum_price_2 += $ld_price_sum;
            }
        }
        $jia_data[] = [
            "<div class='dch-th'>合计</div>",
            "<div class='dch-th'></div>","<div class='dch-th'></div>",
            "<div class='dch-th allpric sum_group_price_2'>{$sum_price_2}</div>",
            "<div class='dch-th'></div>",
        ];

        foreach ($jia_data as $tgd){
            $tgd_i = 0;
            $new_ttav = [];
            foreach ($tgd as $tgdv){
                $new_ttav[] = "{$jia_colspan[$tgd_i]}<div class=''>{$tgdv}</div>";
                $tgd_i++;
            }
            $table_data[] = $new_ttav;
        }

        //------------------------------------铝锭价计价--------------------------------------
        $table_data[] = ["[14:1]"];
        $table_data[] = ["[14:1]<div class='dch-th'>铝锭价计价</div>"];
        $jia_colspan = ["[1:1]","[2:1]","[2:1]","[3:1]","[3:1]","[3:1]"];
        $jia_head = ["板厚","合同铝锭价(元/吨)","下单铝锭价(元/吨)","计算面积(M²)","计算单价(元)","合计金额(元)"];
        $jia_data = [];
        $sum_price_3 = 0;

        foreach ($jia_head as $agk=>$agv){
            $agv = "{$jia_colspan[$agk]}<div class='dch-th'>{$agv}</div>";
            $jia_head[$agk] = $agv;
        }
        $table_data[] = $jia_head;

        //根据板厚数量生成
        $table_group_price_arr = Db::name('mill_order_archives_initial_price')->where(['order_id'=>$data['id'],'type'=>1])->select();
        $tgp_thickness_arr = $table_group_data_type_sarr[$data['id']]['thickness'];
        $tgp_count = (count($tgp_thickness_arr));
        for($pi=0;$pi<$tgp_count;$pi++){
            $tgpv = !empty($table_group_price_arr[$pi])?$table_group_price_arr[$pi]:'';

            $_thickness = key($tgp_thickness_arr);

            $ld_title_0 = !empty($table_group_price_arr[0])?$table_group_price_arr[0]['title']:'';
            $ld_title_class = 'group_lvdingjia';
            if(empty($_thickness)){
                $ld_title_0 = '';
                $ld_title_class = '';
            }

            $i++;
            $ld_id = !empty($tgpv['id'])?$tgpv['id']:'';
            $ld_order_id = !empty($tgpv['order_id'])?$tgpv['order_id']:$data['id'];
            $ld_time = !empty($tgpv['create_time'])?$tgpv['create_time']:time();
            $ld_title = !empty($tgpv['title'])?$tgpv['title']:$ld_title_0;
            $ld_thickness = !empty($tgpv['thickness'])?$tgpv['thickness']:$_thickness;
            $ld_pirce = !empty($tgpv['price'])?$tgpv['price']:0;
            //$ld_area = !empty($tgpv['row_area'])?$tgpv['row_area']:(isset($tgp_thickness_arr[$_thickness])?$tgp_thickness_arr[$_thickness]:'');
            $ld_area = isset($tgp_thickness_arr[$_thickness])?$tgp_thickness_arr[$_thickness]:'';
            $ld_ingots_price = !empty($tgpv['ingots_price'])?$tgpv['ingots_price']:0;
            $ld_ingots_price2 = !empty($tgpv['ingots_price2'])?$tgpv['ingots_price2']:0;

            $ld_type = 1;//类型 0:面积价 1:铝锭价 2:其他价
            $ld_price_sum = round($ld_pirce*floatval($ld_area),2);//四舍五入，取整

            $ld_thickness_html = '
                <input class="form-control" type="hidden" placeholder="请填写板厚" name="price_arr['.$i.'][thickness]" value="'.$ld_thickness.'" data-i="'.$i.'">'.$ld_thickness;

            $ld_input_html = '
                <input class="form-control area" type="hidden" name="price_arr['.$i.'][row_area]" value="'.$ld_area.'" data-area-type="group_row_area_'.$i.'" data-toAreaSum="no" data-i="'.$i.'">'.$ld_area;

            $ld_ingots_price_html = '
                <input type="hidden" name="price_arr['.$i.'][id]" value="'.$ld_id.'">
                <input type="hidden" name="price_arr['.$i.'][order_id]" value="'.$ld_order_id.'">
                <input type="hidden" name="price_arr['.$i.'][create_time]" value="'.$ld_time.'">
                <input type="hidden" name="price_arr['.$i.'][type]" value="'.$ld_type.'">
                    
                <input class="form-control '.$ld_title_class.'" type="hidden" name="price_arr['.$i.'][title]" value="'.$ld_title.'" data-i="'.$i.'">
                <input class="form-control _ingots_price" type="number" name="price_arr['.$i.'][ingots_price]" value="'.$ld_ingots_price.'" data-i="'.$i.'">
                ';
            $ld_ingots_price2_html = '
                <input class="form-control _ingots_price2" type="number" name="price_arr['.$i.'][ingots_price2]" value="'.$ld_ingots_price2.'" data-i="'.$i.'">
                ';
            $ld_area_html = '
                <input class="form-control group_price group_row_area_'.$i.'_val" type="number" name="price_arr['.$i.'][price]" value="'.$ld_pirce.'" data-one_area_sum="'.$ld_area.'" data-i="'.$i.'" data-sum-price="group_price_3">
                
                ';
            if($print){
                $ld_thickness_html = $ld_thickness;
                $ld_ingots_price_html = $ld_ingots_price;
                $ld_ingots_price2_html = $ld_ingots_price2;
                $ld_input_html = $ld_area;
                $ld_area_html = $ld_pirce;
            }
            $ld_price_html = '<span class="group_price_all group_price_3" id="area_sum_'.$i.'">'.$ld_price_sum.'</span>';

            //["板厚","合同铝锭价(元/吨)","下单铝锭价(元/吨)","计算面积(M²)","计算单价(元)","合计金额(元)"];
            $jia_data[] = [$ld_thickness_html,$ld_ingots_price_html,$ld_ingots_price2_html,$ld_input_html,$ld_area_html,$ld_price_html];

            $sum_price_3 += $ld_price_sum;

            unset($tgp_thickness_arr[$_thickness]);
        }
        $jia_data[] = [
            "<div class='dch-th'>合计</div>",
            "<div class='dch-th'></div>","<div class='dch-th'></div>","<div class='dch-th'></div>","<div class='dch-th'></div>",
            "<div class='dch-th allpric sum_group_price_3'>{$sum_price_3}</div>",
        ];

        foreach ($jia_data as $tgd){
            $tgd_i = 0;
            $new_ttav = [];
            foreach ($tgd as $tgdv){
                $new_ttav[] = "{$jia_colspan[$tgd_i]}<div class=''>{$tgdv}</div>";
                $tgd_i++;
            }
            $table_data[] = $new_ttav;
        }

        //----------------------------------------总计------------------------------------------
        $table_data[] = ["[14:1]"];
        $table_data[] = ["[14:1]<div class='dch-th'>总计</div>"];
        $jia_colspan = ["[3:1]","[3:1]","[3:1]","[5:1]"];
        $jia_head = ["基本计价金额(元)","加价计价金额(元)","铝锭计价金额(元)","发货单总计金额(元)"];
        $jia_data = [];

        foreach ($jia_head as $agk=>$agv){
            $agv = "{$jia_colspan[$agk]}<div class='dch-th'>{$agv}</div>";
            $jia_head[$agk] = $agv;
        }
        $table_data[] = $jia_head;

        $sum_info['address_price'] = ($sum_price_1+$sum_price_2+$sum_price_3);
        $jia_data[] = [
            "<div class='dch-th allpric sum_group_price_1' >{$sum_price_1}</div>",
            "<div class='dch-th allpric sum_group_price_2' >{$sum_price_2}</div>",
            "<div class='dch-th allpric sum_group_price_3' >{$sum_price_3}</div>",
            "<div class='dch-th allpric sum_group_price' >{$sum_info['address_price']}</div>",
        ];

        foreach ($jia_data as $tgd){
            $tgd_i = 0;
            $new_ttav = [];
            foreach ($tgd as $tgdv){
                $new_ttav[] = "{$jia_colspan[$tgd_i]}<div class=''>{$tgdv}</div>";
                $tgd_i++;
            }
            $table_data[] = $new_ttav;
        }

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                  
                    $(".dch-th").parents("th,td").addClass("dch-th");
                    //根据页面高度设置滚动条
                    var height = $(window).height();
                    var top = $("#form_group_list_archives_group").offset().top;
                    var bottom = 80;
                    $("#form_group_list_archives_group").css("height",(height-top-bottom)+"px");
                    $("#form_group_list_archives_group").css("overflow-x","scroll");
                    
                    //监听铝锭价设置
                    $("._ingots_price").bind("input propertychange", function() {
                        var ingots_price = $(this).val();
                        var ingots_price2 = $(this).parents("tr").find("._ingots_price2").val();
                        //同步更新铝锭价标题
                        var title = "合同铝锭价"+ingots_price+"元/吨，下单铝锭价"+ingots_price2+"元/吨";
                        $(this).parents("tr").find(".group_lvdingjia").val(title);
                    });
                    //监听下单铝锭价设置
                    $("._ingots_price2").bind("input propertychange", function() {
                        var _ingots_price = $(this).parents("tr").find("._ingots_price").val();
                        var _ingots_price2 = $(this).val();
                        //同步更新铝锭价标题
                        var title = "合同铝锭价"+_ingots_price+"元/吨，下单铝锭价"+_ingots_price2+"元/吨";
                        $(this).parents("tr").find(".group_lvdingjia").val(title);
                    });
                    //监听加价设置
                    $(".group_input").bind("input propertychange", function() {
                        updateSumPrice($(this));
                    });
                    //监听单价设置
                    $(".group_price").bind("input propertychange", function() {
                        updatePrice($(this));
                    });
                    //监听开槽等面积设置
                    $(".area").bind("input propertychange", function() {
                        var obj = $(this);
                        var area = obj.val();
                        var type = obj.data("area-type");
                        var group = obj.data("group");
                        var toAreaSum = obj.data("toAreaSum");
                        var sum_area = 0;
                        
                        if(toAreaSum == "no"){
                            //不更新合计面积
                            sum_area = obj.val();
                        }
                        else {
                            var sum_group_area = 0;
                            //更新合计面积
                            $(".area[data-area-type="+type+"]").each(function() {
                                var each_group = $(this).data("group");
                                var val = parseFloat($(this).val());
                                if(isNaN(val)){
                                    val = 0;
                                }
                                sum_area += val;
                                if(group == each_group){
                                    sum_group_area += val;
                                }
                            });
                            //四舍五入保留六位小数
                            sum_area = Math.round(sum_area*1000000)/1000000;
                            sum_group_area = Math.round(sum_group_area*1000000)/1000000;
                            $("#"+group+" div").text(sum_group_area);
                            $("#"+group+" input").val(sum_group_area);
                            $("."+type+"_sum").text(sum_area);
                            $("#sum_group_"+type).text(sum_area);
                        }
                        
                        //更新合计价格
                        $("."+type+"_row_area").val(sum_area);
                        $("."+type+"_val").data("one_area_sum",sum_area);
                        updatePrice($("."+type+"_val"));
                    
                    });
                    //更新铝板单价
                    function updateSumPrice(obj) {
                        
                        var group = obj.data("group");
                        
                        var sum_price = 0;
                        $("."+group+"_sum_price").each(function() {
                            var price = $(this).val();
                            if(!price)price = 0;
                            sum_price += parseFloat(price);
                        });
                        //console.log(sum_price);
                        //四舍五入，保留2位
                        sum_price = Math.round(sum_price*100)/100;
                        $("#"+group+"_price").val(sum_price);
                        //更新金额
                        updatePrice($("#"+group+"_price"));
                    }
                    //更新合计价格
                    function updatePrice(obj) {
                        var price = obj.val();
                        var price_sum = obj.data("one_area_sum")*price;
                        //四舍五入，保留2位
                        price_sum = Math.round(price_sum*100)/100;
                        var i = obj.data("i");
                        $("#area_sum_"+i).text(price_sum);
                        
                        //当前模块合计
                        var price_i = obj.data("sum-price");
                        var sum_group_price = 0;
                        $("."+price_i).each(function() {
                            sum_group_price += parseFloat($(this).text());
                        });
                        //四舍五入，保留2位
                        sum_group_price = Math.round(sum_group_price*100)/100;
                        $(".sum_"+price_i).text(sum_group_price);
                        
                        //所有合计总和
                        sum_group_price = 0;
                        $(".group_price_all").each(function() {
                            sum_group_price += parseFloat($(this).text());
                        });
                        //四舍五入，保留2位
                        sum_group_price = Math.round(sum_group_price*100)/100;
                        $(".sum_group_price").text(sum_group_price);
                        $("input[name=\'initial_price\']").val(sum_group_price);
                    }
                })
            </script>';

        //CSS
        $css = '<style>
                    #table-list_archives_group,#table-list_archives_group_title {
                        text-align: center;
                        border: none;
                    }
                    #table-list_archives_group th,#table-list_archives_group_title td {
                        text-align: center;
                        font-size: 14px;
                        font-weight: bold!important;
                        border: none;
                    }
                    .dch-th {
                        background-color: #eee;
                        font-weight: bold!important;
                    }
                    .allpric {
                        color: #FF0000;
                    }
                    .block-header {
                        height: 47px;
                        background-color: rgb(51, 102, 204);
                        position: relative;
                        text-align: center;
                        font-size: 22px;
                        font-weight: bold;
                        color: rgb(255, 255, 255);
                        line-height: 47px;
                    }
                    .dch-form-btn {
                        text-align: center;
                    }
                </style>';

        return ['head'=>$table_head,'data'=>$table_data,'js'=>$js,'css'=>$css,'sum_info'=>$sum_info];
    }

    // 打印模板
    //print 1:打印模式 2:导出模式
    public static function toHtml($data = [],$print = 1){

        //缩放比例
        $table_scaling = 1;

        //$html = '<html><style>th{font-size: 18px;font-weight: bold;}td{}</style><body style="margin: 4px;">';
        $html = '<html><style>th{font-size: 12px;font-weight: bold;}td{font-size: 12px;}</style><body style="margin: 4px;">';

        //头部
        $html .= '<table border="1" style="text-align: center;border-collapse: collapse;width: '.(21/$table_scaling).'cm;transform-origin: 0 0;"><thead>
                        <tr><th colspan="13" style="font-size: 25px;font-weight: bold;"><img style="width: 50px;margin-bottom: -20px;" class="td-none" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/logo2.jpg">'.config('web_site_title').'</th></tr>
                    ';
        $table_arr = self::fromArchivesTabale($data,1);
        foreach ($table_arr as $tk=>$tv){
            //头
            if($tk == 'head'){
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tvvv){

                        $v = OrderModel::tableParseCell($tvvv);

                        $html .= '
                            <th rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</th>
                            ';
                    }
                    $html .= '</tr>';
                }
                $html .= '</thead>';
            }
            //体
            elseif($tk == 'data'){
                $html .= '<tbody>';
                foreach ($tv as $tvv){

                    $html .= '<tr>';
                    foreach ($tvv as $tvvv){

                        $v = OrderModel::tableParseCell($tvvv);

                        $v['value'] = str_replace("\n","<br>",$v['value']);
                        $html .= '
                            <td rowspan="'.$v['rowspan'].'" colspan="'.$v['colspan'].'">'.$v['value'].'</td>
                            ';
                    }
                    $html .= '</tr>';
                }
                $html .= '</tbody>';
            }
        }
        $html .= '</table>';

        $js = 'window.print();';
        if($print == 2){
            $js = '$("table").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: "",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "计价单",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });';
        }
        //js
        $html .= '
                    <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script>
                    <script src="'.config('template.tpl_replace_string')['__STATIC__'].'/common/js/jquery.table2excel.js?v='.date('Ymd').'"></script>
                    <script type="text/javascript">
                        //去除边框
                        $(".td-none").parent().css("border-style","hidden")
                        //设置头部边框
                        $(".td-top").parent().css("border-top","black");
                        //设置底部边框
                        $(".td-bottom").parent().css("border-bottom","black");
                        //设置高度
                        $(".td-50").parent().css("height","50px");
                        //设置向下对齐
                        $(".text-bottom").parent().css("vertical-align","bottom");
                        //设置文字上下间距
                        $(".text-height").parent().css("line-height","28px");
                        //设置文字缩放比例
                        $("th,td").css("-webkit-transform","scale('.$table_scaling.')");
                        //设置文字缩放后左对齐
                        $(".scale-left").parent().css("transform-origin","0");
                        
                        '.$js.'
                    </script>';

        return $html;
    }

    //更新发货金额
    public static function updateAddressPrice($order_ids = '',$address_sns = ''){

        //-----------------计价用的字段---------------------
        $archives_fields = [];
        foreach (ArchivesModel::$layui_fields as $lhv){
            if($lhv['field'] == 'number')$archives_fields["COUNT(g.id) as number"] = $lhv['title'];
            elseif($lhv['field'] == 'row_area')$archives_fields["(COUNT(g.id)*FORMAT(a.one_area,6)) as row_area"] = $lhv['title'];
            else $archives_fields["a.{$lhv['field']}"] = $lhv['title'];
        }
        $archives_fields['FROM_UNIXTIME(o.archives_bill_time,\'%Y-%m-%d\') as archives_bill_time'] = '来单日期';
        $archives_field = implode(',',array_keys($archives_fields)).",(COUNT(g.id)*a.slot) as slot,(COUNT(g.id)*a.weld) as weld,(COUNT(g.id)*a.torque) as torque,g.order_id";

        //加上发货时间
        $archives_field .= ",g.address_date,g.address_time";

        //发货状态
        GiveModel::init();
        $give_status = GiveModel::$last_give_status;

        //发货单号整合
        $address_list = [];

        //遍历工程批次
        $order_ids = explode(',',$order_ids);
        foreach ($order_ids as $order_id){

            $where = ['g.order_id'=>$order_id,'g.status'=>$give_status];

            //获取该批次所有的发货单号
            if(empty($address_sns)){
                $address_where = $where;
                $address_sns = Db::name('mill_order_archives_give')->alias('g')->where($address_where)->group('address_sn')->column('address_sn');
            }
            //指定发货单号
            else $address_sns = explode(',',$address_sns);

            //遍历发货单
            if(!empty($address_sns)){
                foreach ($address_sns as $address_sn){
                    //发货单号整合
                    if(!empty($address_sn))$address_list[$address_sn]['address_sn'] = $address_sn;

                    $where['g.address_sn'] = $address_sn;

                    $archives_list = Db::name('mill_order_archives_give')
                        ->alias('g')
                        ->field($archives_field)
                        ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                        ->leftJoin('mill_order o','o.id=g.order_id')
                        ->where($where)
                        ->group('a.id')
                        ->order('a.sort asc')
                        ->select();

                    //如果发货单号对应的产品不存在，则删除相关的发货单信息
                    if(empty($archives_list)){
                        Db::name('mill_order_archives_address_price')->where(['order_id'=>$order_id,'address_sn'=>$address_sn])->delete();
                        continue;
                    }

                    $order = Db::name('mill_order')
                        ->alias('o')
                        ->field('o.*,ms.staff as sales,c.company,c.mobile as c_mobile,0 as number_sum,0 as area_sum,0 as slot,0 as weld,0 as torque')
                        ->leftJoin('mill_staff ms','o.sales_id=ms.id','left')
                        ->leftJoin('mill_client c','c.id=o.client_id','left')
                        ->where(['o.id'=>$archives_list[0]['order_id']])
                        ->find();

                    foreach ($archives_list as &$v){
                        $order['slot'] += $v['slot'];
                        $order['weld'] += $v['weld'];
                        $order['torque'] += $v['torque'];
                        $order['number_sum'] += $v['number'];
                        $order['area_sum'] += $v['row_area'];

                        $order['address_date'] = $v['address_date'];
                        $order['address_time'] = $v['address_time'];

                        unset($v['slot']);
                        unset($v['weld']);
                        unset($v['torque']);
                        unset($v['order_id']);
                        unset($v['address_date']);
                        unset($v['address_time']);
                    }

                    //面积表信息
                    $order['table_archives']['head'] = array_values($archives_fields);
                    $order['table_archives']['data'] = $archives_list;

                    //表头
                    $order['table_head'] = [];
                    $order['table_head'] = [];

                    //基本计价
                    $order['table_archives_group']['head'] = ['厚度','颜色','铝板版型','合计数量(件)','合计面积(M²)','单价(元)','合计金额(元)'];

                    $join = [['mill_order_archives_give g','a.id=g.archives_id','left'],['mill_order o','a.order_id=o.id','left']];
                    $table_group_field = "a.thickness,a.color,a.model,SUM(g.number) AS number_sum,ROUND(SUM(a.one_area),4) AS one_area_sum,group_concat(a.id) as archives_ids,a.order_id";
                    $order['table_archives_group']['data'] = ArchivesModel::getList('',$table_group_field,'','a.thickness,a.color,a.model',$join,$where);

                    $sum_info = (self::fromArchivesTabale($order,1));
                    $sum_info = $sum_info['sum_info'];

                    //获取该工程的发货单金额
                    $address_price_info = Db::name('mill_order_archives_address_price')->where(['order_id'=>$order_id,'address_sn'=>$address_sn])->find();
                    //新增该工程的发货单金额
                    if(empty($address_price_info)){
                        $address_price_add = [
                            'address_sn'        =>  $address_sn,
                            'order_pid'         =>  $order['order_pid'],
                            'order_id'          =>  $order['id'],
                            'archives_sn'       =>  $order['archives_sn'],
                            'address_date'      =>  empty($order['address_date'])?date('Y-m-d'):$order['address_date'],
                            'address_time'      =>  empty($order['address_time'])?time():$order['address_time'],
                        ];
                        $address_price_add = array_merge($address_price_add,$sum_info);
                        Db::name('mill_order_archives_address_price')->insert($address_price_add);
                    }
                    //更新该工程的发货单金额
                    else Db::name('mill_order_archives_address_price')->where(['order_id'=>$order_id,'address_sn'=>$address_sn])->update($sum_info);

                }
            }

            //该批次的发货总金额
            $where = ['order_id'=>$order_id];
            $address_info = Db::name('mill_order_archives_address_price')->field('sum(address_price) as address_price,sum(address_number) as address_number,sum(address_area) as address_area')->where($where)->find();
            //更新工程的发货总金额
            Db::name('mill_order')->where(['id'=>$order_id])->update($address_info);

        }

        //遍历整合的发货单号，并更新发货单的总金额
        foreach ($address_list as $address){
            $where = ['address_sn'=>$address['address_sn']];
            $sum_info = Db::name('mill_order_archives_address_price')->field('sum(address_price) as address_price,sum(address_number) as address_number,sum(address_area) as address_area')->where($where)->find();

            //如果发货单号对应的产品不存在，则删除相关的发货单信息
            $count = Db::name('mill_order_archives_give')->where($where)->count();
            if(empty($count))Db::name('mill_order_archives_address')->where($where)->delete();
            else Db::name('mill_order_archives_address')->where($where)->update($sum_info);
        }

    }

}
